const download = require('download-git-repo')


function downloadRepo(url, distDir, options = {clone: true}){
  return new Promise((resolve, reject) => {
    download(url, distDir, options, function(err){
      if(err){
        console.error(`download file from ${url} failed!`)
        reject(err)
      } else {
        resolve(distDir)
      }
    })
  })
}

/**
 * @description: 是否为绝对地址
 * @param {String} url 
 * @returns {Boolean}
 */
 function isAbsoluteUrl(url) {
  // const reg = new RegExp("^(https):\/\/[\\w\\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?")
  const reg = new RegExp("^(https):\/\/[\\w-_]+(\\.)+[\\w\\-_]+")
  return reg.test(url)
}

function getRepoUrlByAuth(username, password, url){
  if(isAbsoluteUrl(url)) {
    const prefix = 'https://'
    const repoUrl = url.substring(prefix.length)
    let downloadUrl = `direct:${prefix}${encodeURIComponent(username)}:${encodeURIComponent(password)}@${repoUrl}`
    if(repoUrl.indexOf('#') <= -1){
      downloadUrl += '#master'
    }
    return [true, downloadUrl]
  }
  return [false, '请输入绝对地址，如：https://gitee.com/demoRepo/']
}
module.exports = {
  downloadRepo,
  getRepoUrlByAuth,
  isAbsoluteUrl
}